import os
import datetime
import time
import shutil
import psutil
from config import FILE_PATH


def time_task():
    while True:
        try:
            folder_path = FILE_PATH
            # 获取当前日期
            now = datetime.datetime.now()
            current_date = now.date()
            current_time_ms = int(time.time() * 1000)  # 当前时间（毫秒）
            one_hour_ms = 3600 * 1000  # 一小时（毫秒）
            if True:
                # 遍历指定路径下的文件夹
                for folder_name in os.listdir(folder_path):

                    delete_time = 1

                    target_file = folder_path + "/" + folder_name + "/" + folder_name
                    for target_name in os.listdir(target_file):
                        # target_name 时间  2024-11-21
                        # print(target_name)
                        folder_date = datetime.datetime.strptime(target_name, '%Y-%m-%d').date()
                        delta = current_date - folder_date
                        # print(delta.days)
                        # 判断文件夹日期是否大于1天，如果大于一天，直接删除
                        if delta.days >= delete_time:
                            folder_full_path = os.path.join(target_file, target_name)
                            # 删除文件夹及其内容
                            try:

                                # 遍历当前目录下的所有文件
                                for file in os.listdir(folder_full_path):
                                    file_path = os.path.join(folder_full_path, file)
                                    if os.path.isfile(file_path):
                                        try:
                                            # 删除文件
                                            os.remove(file_path)
                                            print(f"文件超过一天 Deleted file: {file_path}")
                                        except OSError as e:
                                            print(f"Error deleting file {file_path}: {e}")
                            except Exception as e:
                                print(f"An error occurred: {e}")
                        # 如果小于一天
                        else:
                            folder_full_path = os.path.join(target_file, target_name)
                            # 删除文件夹及其内容
                            try:

                                # 遍历当前目录下的所有文件
                                for file in os.listdir(folder_full_path):
                                    file_path = os.path.join(folder_full_path, file)
                                    if os.path.isfile(file_path):
                                        # 获取文件扩展名
                                        file_name, file_extension = os.path.splitext(file)
                                        # 如果后缀是.mp4，删除文件
                                        if file_extension.lower() == '.mp4':
                                            os.remove(file_path)
                                            print(f"Deleted MP4: {file_path}")
                                        # 如果后缀是.log或者没有后缀，如果超过一小时，删除文件
                                        if not file_extension or file_extension.lower() == '.log':
                                            file_timestamp_ms = int(file_name)
                                            # 检查文件名的时间戳是否大于当前时间一小时 1732239167490
                                            if file_timestamp_ms < current_time_ms - one_hour_ms:
                                                os.remove(file_path)
                                                print(f"文件超过一小时，删除: {file_path}")
                            except Exception as e:
                                print(f"An error occurred: {e}")
            # # 获取磁盘使用情况
            # disk_usage = psutil.disk_usage('/')
            #TimedTasksSecond.py
            # # 计算磁盘使用百分比
            # disk_percent = disk_usage.percent
            # print(disk_percent)
            # # 指定删除的文件夹路径
            #
            # # 判断磁盘使用百分比是否大于60%
            # if disk_percent > 60:
            #
            #     # 遍历指定路径下的文件夹
            #     delete_list = {}
            #     for folder_name in os.listdir(folder_path):
            #         target_file = folder_path + "/" + folder_name + "/" + folder_name
            #         for target_name in os.listdir(target_file):
            #             print(target_name)
            #             folder_date = datetime.datetime.strptime(target_name, '%Y-%m-%d').date()
            #             delta = current_date - folder_date
            #             print(delta.days)
            #             # 判断文件夹日期是否大于七天
            #             if delta.days not in delete_list.keys():
            #                 delete_list[delta.days] = [os.path.join(target_file, target_name)]
            #             else:
            #                 delete_list[delta.days] = delete_list[delta.days].append(os.path.join(target_file, target_name))
            #     delete_key = sorted(list(delete_list.keys()))
            #     delete_num = int(len(delete_key) * 0.1)
            #     for key in delete_key[:delete_num]:
            #         try:
            #             shutil.rmtree(delete_list[key])
            #             print(f"删除文件夹: {delete_list[key]}")
            #         except Exception as e:
            #             print(f"删除文件夹失败: {delete_list[key]}, {e}")
        except Exception as e:
            print(str(e))
            continue
        finally:
            time.sleep(30)
